package com.hcloud.auth.api.util;

import com.hcloud.auth.api.user.HcloudUserDetails;
import com.hcloud.system.core.bean.user.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 方便获取当前用户，当前权限等
 *
 * @Auther hepangui
 * @Date 2018/11/14
 */
public class AuthUtil {
    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public static User getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof HcloudUserDetails) {
            return ((HcloudUserDetails)principal).getBaseUser();
        }
        return null;
    }

    public static String getClientId() {
        Authentication authentication = getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
            return auth2Authentication.getOAuth2Request().getClientId();
        }
        return null;
    }

    /**
     * 获取用户
     */
    public static User getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    /**
     * 获取权限信息
     */
    public static Set<String> getAuthority() {
        Authentication authentication = getAuthentication();
        var set = authentication.getAuthorities().stream().map(a -> ((GrantedAuthority) a).getAuthority()).collect(Collectors.toSet());
        return set;
    }
}
